package com.biz.impl;


import com.dto.BaseInfoDTO;
import com.bean.Role;
import com.bean.User;
import com.biz.UserBizService;
import com.dto.user.UserBaseInfoDTO;
import com.dto.user.UserTokenDTO;
import com.dto.user.UserUpdateDTO;
import com.exception.BizException;
import com.exception.userexcetion.*;
import com.exception.ISQLException;
import com.myenum.*;


import com.servicedao.RoleService;
import com.servicedao.UserRoleService;
import com.servicedao.UserService;
import com.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author FatterShadystart
 * @create 2023-02-09 14:41
 */
@Service
@Slf4j
public class UserBizServiceImpl implements UserBizService {
    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RoleService roleService;


    @Resource
    private TransactionTemplate transactionTemplate;

    private static final Integer RESULT_RETURN_NUM = 1;
    private static final String USER_ROLE_USER = "user";
    private static final String USER_ROLE_ADMIN = "admin";

    @Override
    public Long queryAdminId() {
        User user = new User();
        user.setEmail(BizEnumString.DEFAULT_ADMIN_ACCOUNT.getMsg());
        return userService.selectUserByEmailList(ParamUtil.buildUserListLogin(user), BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()).get(0).getUserId();
    }

    @Override
    public Integer checkAdmin(Long userId) {
        User user = new User();
        user.setUserId(userId);
        return userService.selectUserList(ParamUtil.buildUserListLogin(user), BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()).get(0).getStatus();
    }

    @Override
    public Map<String, List<User>> queryUserCUOR(List<User> userList) {
        List<User> creatorList = new ArrayList<>();
        List<User> updatorList = new ArrayList<>();
        Map<String, List<User>> resultMap = new HashMap();
        for (User user : userList) {
            User creatorUser = new User();
            User updatorUser = new User();
            User creator = userService.selectUserByCreator(user);
            User updator = userService.selectUserByUpdator(user);
            if (!ObjectUtils.isEmpty(creator)) {
                creatorUser.setEmail(creator.getEmail());
            }
            if (!ObjectUtils.isEmpty(updator)) {
                updatorUser.setEmail(updator.getEmail());
            }
            creatorList.add(creatorUser);
            updatorList.add(updatorUser);
        }
        log.info("creatorList:{}", creatorList);
        log.info("updatorList:{}", updatorList);
        resultMap.put("creatorList", creatorList);
        resultMap.put("updatorList", updatorList);
        return resultMap;
    }

    @Override
    public Map<String, Object> queryUserByCondition(UserBaseInfoDTO userBaseInfoDTO) {
        List<User> userList = ParamUtil.buildUserListLogin(userBaseInfoDTO.getUser());
        Map<String, Object> resultMap = new HashMap();
        Map<String, Integer> pageStartAndEnd = PageUtil.getPageStartAndEnd(userBaseInfoDTO.getBaseInfoDTO());
        Integer start = pageStartAndEnd.get(BizEnumString.START.getMsg());
        Integer end = pageStartAndEnd.get(BizEnumString.END.getMsg());
        //查询UserList
        List<User> userListQuery = userService.selectUserListByCondition(userList, start, end);
        if (userListQuery.isEmpty()) {
            resultMap.put("userRoleList", null);
            resultMap.put("allUserCount", BizEnumData.DEFAULT_QUERY_COUNT.getData());
            return resultMap;
        }
        //查询UserRoleList
        List<User> userRoleList = userService.selectUserListAndRoleList(userListQuery, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData());
        //查询总记录数
        Integer allUserCount = userService.selectUserListByCondition(userList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData()).size();
        log.info("userRoleList:{}", userRoleList);
        log.info("allUserCount:{}", allUserCount);
        resultMap.put("userRoleList", userRoleList);
        resultMap.put("allUserCount", allUserCount);
        return resultMap;

    }

    @Override
    public Map<String, Object> queryUserAllByPage(UserBaseInfoDTO userBaseInfoDTO) {
        Map<String, Object> resultMap = new HashMap();
        Map<String, Integer> pageStartAndEnd = PageUtil.getPageStartAndEnd(userBaseInfoDTO.getBaseInfoDTO());
        Integer start = pageStartAndEnd.get(BizEnumString.START.getMsg());
        Integer end = pageStartAndEnd.get(BizEnumString.END.getMsg());
        //查询UserList
        List<User> userList = userService.selectAllUserList(start, end);
        //查询UserRoleList
        List<User> userRoleList = userService.selectUserListAndRoleList(userList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData());
        //查询总记录数
        Integer allUserCount = userService.selectAllUserCount();
        log.info("userRoleList:{}", userRoleList);
        log.info("allUserCount:{}", allUserCount);
        resultMap.put("userRoleList", userRoleList);
        resultMap.put("allUserCount", allUserCount);
        return resultMap;
    }

    @Override
    public void insertUser(UserBaseInfoDTO userBaseInfoDTO) throws InsertException {
        User user = userBaseInfoDTO.getUser();
        Role role = userBaseInfoDTO.getRole();

        List<User> userList = ParamUtil.buildUserListInsert(user);
        List<Role> roleList = ParamUtil.buildRoleList(role.getUserRole());

        //判断是否已注册,已注册就抛异常
        if (!ObjectUtils.isEmpty(userService.selectUserByEmailList(userList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()))) {
            throw new InsertException(ExceptionEnum.USER_SELECT_RETURN_SAME_EXCEPTION.getErrorMsg());
        }


        TransactionUtil.checkTransactionInsert(transactionTemplate.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus transactionStatus) {
                try {
                    Integer userInsResult = userService.insertBatch(userList);
                    log.info("userInsResult:{}", userInsResult);
                    Integer userRoleInsResult = userRoleService.insert(user.getUserId(), roleService.selectRoleListByUserRole(roleList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()).get(0).getRoleId());
                    log.info("userRoleInsResult:{}", userRoleInsResult);
                    if (!RESULT_RETURN_NUM.equals(userInsResult)) {
                        log.error("userInsResult:{}", userInsResult);
                        throw new ISQLException(ExceptionEnum.INSERT_RETURN_LINE_EXCEPTION.getErrorMsg());
                    }
                    if (!RESULT_RETURN_NUM.equals(userRoleInsResult)) {
                        log.error("userRoleInsResult:{}", userRoleInsResult);
                        throw new ISQLException(ExceptionEnum.INSERT_RETURN_LINE_EXCEPTION.getErrorMsg());
                    }
                } catch (ISQLException e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    log.error("e:{}", e.getMessage());
                    return false;
                }
                return true;
            }
        }));
    }


    @Transactional
    @Override
    public void updateUser(UserUpdateDTO userUpdateDTO,Long updatorId) throws UpdateException {
        User user = userUpdateDTO.getUser();
        Boolean isAdmin = userUpdateDTO.getIsAdmin();
        //未设置管理员权限
        if (!isAdmin) {
            List<User> userList = ParamUtil.buildUserListUpdate(user);
            List<User> userListQuery = userService.selectUserList(userList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData());
            List<User> userRoleList = userService.selectUserListAndRoleList(userListQuery, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData());
            //拷贝数据用于更新
            User userListItem = userList.get(0);
            User userListQueryItem = userListQuery.get(0);
            userListQueryItem.setNickName(userListItem.getNickName());
            userListQueryItem.setEmail(userListItem.getEmail());
            userListQueryItem.setPassword(userListItem.getPassword());
            userListQueryItem.setPhone(userListItem.getPhone());
            userListQueryItem.setStatus(userListItem.getStatus());
            userListQueryItem.setAddress(userListItem.getAddress());
            userListQueryItem.setUpdatorId(updatorId);

            //如果已经是管理员,则需要先删除UserRole表，再修改User表
            if (userRoleList.get(0).getRoleList().size() > 1) {
                TransactionUtil.checkTransactionUpdate(transactionTemplate.execute(new TransactionCallback<Boolean>() {
                    @Override
                    public Boolean doInTransaction(TransactionStatus transactionStatus) {
                        try {
                            //删除UserRole表
                            Role role = roleService.selectRoleListByUserRole(ParamUtil.buildRoleList(RoleEnum.ADMIN.getType()), BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()).get(0);
                            Integer userRoleDeleteResult = userRoleService.deleteBatch(ParamUtil.buildUserRoleIdList(userRoleService.selectByUserIdAndRoleId(user, role)));
                            //修改User表
                            Integer userUpdateResult = userService.updateBatch(userListQuery);
                            if (!RESULT_RETURN_NUM.equals(userUpdateResult)) {
                                log.error("userUpdateResult:{}", userUpdateResult);
                                throw new ISQLException(ExceptionEnum.UPDATE_RETURN_LINE_EXCEPTION.getErrorMsg());
                            }
                            if (!RESULT_RETURN_NUM.equals(userRoleDeleteResult)) {
                                log.error("userRoleDeleteResult:{}", userRoleDeleteResult);
                                throw new ISQLException(ExceptionEnum.UPDATE_RETURN_LINE_EXCEPTION.getErrorMsg());
                            }
                        } catch (ISQLException e) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            log.error("e:{}", e.getMessage());
                            return false;
                        }
                        return true;
                    }
                }));
            }

            //否则直接修改user表
            else {
                TransactionUtil.checkTransactionUpdate(transactionTemplate.execute(new TransactionCallback<Boolean>() {
                    @Override
                    public Boolean doInTransaction(TransactionStatus transactionStatus) {
                        try {
                            //修改user表
                            Integer userUpdateResult = userService.updateBatch(userListQuery);
                            if (!RESULT_RETURN_NUM.equals(userUpdateResult)) {
                                log.error("userUpdateResult:{}", userUpdateResult);
                                throw new ISQLException(ExceptionEnum.UPDATE_RETURN_LINE_EXCEPTION.getErrorMsg());
                            }
                        } catch (ISQLException e) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            log.error("e:{}", e.getMessage());
                            return false;
                        }
                        return true;
                    }
                }));
            }

        }
        //设置管理员权限
        if (isAdmin) {
            List<User> userList = ParamUtil.buildUserListUpdate(user);
            List<User> userListQuery = userService.selectUserList(userList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData());
            List<User> userRoleList = userService.selectUserListAndRoleList(userListQuery, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData());
            //拷贝数据用于更新
            User userListItem = userList.get(0);
            User userListQueryItem = userListQuery.get(0);
            userListQueryItem.setNickName(userListItem.getNickName());
            userListQueryItem.setEmail(userListItem.getEmail());
            userListQueryItem.setPassword(userListItem.getPassword());
            userListQueryItem.setPhone(userListItem.getPhone());
            userListQueryItem.setStatus(userListItem.getStatus());
            userListQueryItem.setAddress(userListItem.getAddress());
            userListQueryItem.setUpdatorId(updatorId);

            //如果已经是管理员
            if (userRoleList.get(0).getRoleList().size() > 1) {
                //直接修改user表
                TransactionUtil.checkTransactionUpdate(transactionTemplate.execute(new TransactionCallback<Boolean>() {
                    @Override
                    public Boolean doInTransaction(TransactionStatus transactionStatus) {
                        try {
                            Integer userUpdateResult = userService.updateBatch(userListQuery);
                            if (!RESULT_RETURN_NUM.equals(userUpdateResult)) {
                                log.error("userUpdateResult:{}", userUpdateResult);
                                throw new ISQLException(ExceptionEnum.UPDATE_RETURN_LINE_EXCEPTION.getErrorMsg());
                            }
                        } catch (ISQLException e) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            log.error("e:{}", e.getMessage());
                            return false;
                        }
                        return true;
                    }
                }));
            }
            //否则需要先插入UserRole表，再修改user表
            else {
                TransactionUtil.checkTransactionUpdate(transactionTemplate.execute(new TransactionCallback<Boolean>() {
                    @Override
                    public Boolean doInTransaction(TransactionStatus transactionStatus) {
                        try {
                            //插入UserRole表
                            Role role = roleService.selectRoleListByUserRole(ParamUtil.buildRoleList(RoleEnum.ADMIN.getType()), BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()).get(0);
                            Integer userRoleInsertResult = userRoleService.insert(user.getUserId(), role.getRoleId());
                            //修改user表
                            Integer userUpdateResult = userService.updateBatch(userListQuery);
                            if (!RESULT_RETURN_NUM.equals(userUpdateResult)) {
                                log.error("userUpdateResult:{}", userUpdateResult);
                                throw new ISQLException(ExceptionEnum.UPDATE_RETURN_LINE_EXCEPTION.getErrorMsg());
                            }
                            if (!RESULT_RETURN_NUM.equals(userRoleInsertResult)) {
                                log.error("userRoleInsertResult:{}", userRoleInsertResult);
                                throw new ISQLException(ExceptionEnum.UPDATE_RETURN_LINE_EXCEPTION.getErrorMsg());
                            }
                        } catch (ISQLException e) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            log.error("e:{}", e.getMessage());
                            return false;
                        }
                        return true;
                    }
                }));
            }
         }
        return;


    }

    @Transactional
    @Override
    public void deleteBatchUser(List<Long> userIdList, Long updatorId) throws DeleteException {
        List<User> userList = ParamUtil.buildUserListByUserIdList(userIdList);
        List<Role> roleList = ParamUtil.buildUserListByUserRoleList(userList.size(), RoleEnum.USER.getType());
        List<User> userListQuery = userService.selectUserListAndRoleList(userList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData()).stream().filter(
                item -> {
                    if (item.getRoleList().size() > 1) {
                        return false;
                    }
                    return true;
                }

        ).collect(Collectors.toList());
        userListQuery.forEach(
                item -> item.setUpdatorId(updatorId));
        if (CollectionUtils.isEmpty(userListQuery)) {
            throw new DeleteException(ExceptionEnum.DELETE_RETURN_LINE_EXCEPTION.getErrorMsg());
        }

        TransactionUtil.checkTransactionDelete(transactionTemplate.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus transactionStatus) {
                try {
                    List<Long> userRoleIdList = new ArrayList();
                    for (int i = 0; i < userListQuery.size(); i++) {
                        User userListQueryItem = userListQuery.get(i);
                        Role roleListQueryItem = roleService.selectRoleListByUserRole(roleList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()).get(0);
                        Long userIdAndRoleId = userRoleService.selectByUserIdAndRoleId(userListQueryItem, roleListQueryItem);
                        userRoleIdList.add(userIdAndRoleId);
                    }
                    //删user表
                    Integer userDeleteResult = userService.deleteBatch(userListQuery);
                    //删中间表
                    Integer userRoleDeleteResult = userRoleService.deleteBatch(userRoleIdList);
                    log.info("userDeleteResult:{}", userDeleteResult);
                    log.info("userRoleDeleteResult:{}", userRoleDeleteResult);
                    if (!Integer.valueOf(userRoleIdList.size()).equals(userDeleteResult)) {
                        log.error("userDeleteResult:{}", userDeleteResult);
                        throw new ISQLException(ExceptionEnum.DELETE_RETURN_LINE_EXCEPTION.getErrorMsg());
                    }
                    if (!Integer.valueOf(userRoleIdList.size()).equals(userRoleDeleteResult)) {
                        log.error("userRoleDeleteResult:{}", userRoleDeleteResult);
                        throw new ISQLException(ExceptionEnum.DELETE_RETURN_LINE_EXCEPTION.getErrorMsg());
                    }
                } catch (ISQLException e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    log.error("e:{}", e.getMessage());
                    return false;
                }
                return true;
            }
        }));
    }


    @Transactional
    @Override
    public void deleteUser(UserBaseInfoDTO userBaseInfoDTO) throws DeleteException {
        User user = userBaseInfoDTO.getUser();
        Role role = userBaseInfoDTO.getRole();
        BaseInfoDTO baseInfoDTO = userBaseInfoDTO.getBaseInfoDTO();
        List<User> userList = ParamUtil.buildUserListRegister(user, baseInfoDTO);
        List<Role> roleList = ParamUtil.buildRoleList(role.getUserRole());
        List<User> userListQuery = userService.selectUserByEmailList(userList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData());
        if (userListQuery.isEmpty()) {
            throw new DeleteException(ExceptionEnum.DELETE_RETURN_LINE_EXCEPTION.getErrorMsg());
        }
        TransactionUtil.checkTransactionDelete(transactionTemplate.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus transactionStatus) {
                try {
                    User userListQueryItem = userListQuery.get(0);
                    Role roleListQueryItem = roleService.selectRoleListByUserRole(roleList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()).get(0);
                    Long userRoleId = userRoleService.selectByUserIdAndRoleId(userListQueryItem, roleListQueryItem);
                    //删user表
                    Integer userDeleteResult = userService.deleteBatch(userListQuery);
                    //删中间表
                    Integer userRoleDeleteResult = userRoleService.deleteBatch(ParamUtil.buildUserRoleIdList(userRoleId));
                    log.info("userDeleteResult:{}", userDeleteResult);
                    log.info("userRoleDeleteResult:{}", userRoleDeleteResult);
                    if (!RESULT_RETURN_NUM.equals(userDeleteResult)) {
                        log.error("userDeleteResult:{}", userDeleteResult);
                        throw new ISQLException(ExceptionEnum.DELETE_RETURN_LINE_EXCEPTION.getErrorMsg());
                    }
                    if (!RESULT_RETURN_NUM.equals(userRoleDeleteResult)) {
                        log.error("userRoleDeleteResult:{}", userRoleDeleteResult);
                        throw new ISQLException(ExceptionEnum.DELETE_RETURN_LINE_EXCEPTION.getErrorMsg());
                    }
                } catch (ISQLException e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    log.error("e:{}", e.getMessage());
                    return false;
                }
                return true;
            }
        }));
    }


    @Override
    public UserTokenDTO loginUser(UserBaseInfoDTO userBaseInfoDTO) throws LoginException {
        User user = userBaseInfoDTO.getUser();
        List<User> userList = ParamUtil.buildUserListLogin(user);

        //判断是否已注册，没注册就抛异常
        List<User> userListQueryByEmail = userService.selectUserByEmailList(userList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData());
        if (ObjectUtils.isEmpty(userListQueryByEmail)) {
            throw new LoginException(ExceptionEnum.USER_SELECT_RETURN_NO_EMAIL_EXCEPTION.getErrorMsg());
        }

        //判断账号密码是否正确，不正确就抛异常
        if (!PassWordUtil.matchPassword(user.getPassword(), userListQueryByEmail.get(0).getPassword())) {
            throw new LoginException(ExceptionEnum.USER_SELECT_RETURN_FAILED_PASSWORD_EXCEPTION.getErrorMsg());
        }

        //判断账号是否被冻结，被冻结就抛异常
        if (BizEnumData.FREEZE_FLAG.getData().equals(userListQueryByEmail.get(0).getStatus())) {
            throw new LoginException(ExceptionEnum.USER_SELECT_RETURN_FREEZE_EXCEPTION.getErrorMsg());
        }


        //判断传过来的用户账号信息中是否有user角色
        if (
                userService.selectUserListAndRoleList(userListQueryByEmail, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData()).get(0).getRoleList().stream().noneMatch(
                        res -> USER_ROLE_USER.equals(res.getUserRole())
                )
        ) {
            throw new LoginException(ExceptionEnum.USER_SELECT_RETURN_NO_EXIST_USER_ROLE_PERMISSION_EXCEPTION.getErrorMsg());
        }

        //签发JWT
        User loginUser = userListQueryByEmail.get(0);
        UserTokenDTO userTokenDTO = new UserTokenDTO();
        userTokenDTO.setUserId(loginUser.getUserId());
        userTokenDTO.setEmail(loginUser.getEmail());
        userTokenDTO.setStatus(loginUser.getStatus());
        userTokenDTO.setToken(JwtUtil.sign(userTokenDTO, DateUtils.getNowTimeStamp()));
        return userTokenDTO;
    }

    @Override
    public UserTokenDTO loginUserAdmin(UserBaseInfoDTO userBaseInfoDTO) throws LoginException {
        User user = userBaseInfoDTO.getUser();
        List<User> userList = ParamUtil.buildUserListLogin(user);

        //判断是否已注册，没注册就抛异常
        List<User> userListQueryByEmail = userService.selectUserByEmailList(userList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData());
        if (ObjectUtils.isEmpty(userListQueryByEmail)) {
            throw new LoginException(ExceptionEnum.USER_SELECT_RETURN_NO_EMAIL_EXCEPTION.getErrorMsg());
        }

        //判断账号密码是否正确，不正确就抛异常
        if (!PassWordUtil.matchPassword(user.getPassword(), userListQueryByEmail.get(0).getPassword())) {
            throw new LoginException(ExceptionEnum.USER_SELECT_RETURN_FAILED_PASSWORD_EXCEPTION.getErrorMsg());
        }

        //判断账号是否被冻结，被冻结就抛异常
        if (BizEnumData.FREEZE_FLAG.getData().equals(userListQueryByEmail.get(0).getStatus())) {
            throw new LoginException(ExceptionEnum.USER_SELECT_RETURN_FREEZE_EXCEPTION.getErrorMsg());
        }


        //判断传过来的用户账号信息中是否有admin角色
        if (
                userService.selectUserListAndRoleList(userListQueryByEmail, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData()).get(0).getRoleList().stream().noneMatch(
                        res -> USER_ROLE_ADMIN.equals(res.getUserRole())
                )
        ) {
            throw new LoginException(ExceptionEnum.USER_SELECT_RETURN_NO_EXIST_USER_ROLE_PERMISSION_EXCEPTION.getErrorMsg());
        }

        //签发JWT
        User loginUser = userListQueryByEmail.get(0);
        UserTokenDTO userTokenDTO = new UserTokenDTO();
        userTokenDTO.setUserId(loginUser.getUserId());
        userTokenDTO.setEmail(loginUser.getEmail());
        userTokenDTO.setStatus(loginUser.getStatus());
        userTokenDTO.setToken(JwtUtil.sign(userTokenDTO, DateUtils.getNowTimeStamp()));
        return userTokenDTO;

    }


    @Transactional
    @Override
    public void registerUser(UserBaseInfoDTO userBaseInfoDTO) throws RegisterException {

        User user = userBaseInfoDTO.getUser();
        Role role = userBaseInfoDTO.getRole();
        BaseInfoDTO baseInfoDTO = userBaseInfoDTO.getBaseInfoDTO();

        List<User> userList = ParamUtil.buildUserListRegister(user, baseInfoDTO);
        List<Role> roleList = ParamUtil.buildRoleList(role.getUserRole());

        //判断是否已注册,已注册就抛异常
        if (!ObjectUtils.isEmpty(userService.selectUserByEmailList(userList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()))) {
            throw new RegisterException(ExceptionEnum.USER_SELECT_RETURN_SAME_EXCEPTION.getErrorMsg());
        }

        //判断是否已有当前角色，参数如果没有当前角色，就抛异常
        if (ObjectUtils.isEmpty(roleService.selectRoleListByUserRole(roleList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()))) {
            throw new RegisterException(ExceptionEnum.USER_SELECT_RETURN_NO_EXIST_USER_ROLE_EXCEPTION.getErrorMsg());
        }

        TransactionUtil.checkTransactionRegister(transactionTemplate.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus transactionStatus) {
                try {
                    Integer userInsResult = userService.insertBatch(userList);
                    log.info("userInsResult:{}", userInsResult);
                    Integer userRoleInsResult = userRoleService.insert(user.getUserId(), roleService.selectRoleListByUserRole(roleList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()).get(0).getRoleId());
                    log.info("userRoleInsResult:{}", userRoleInsResult);
                    if (!RESULT_RETURN_NUM.equals(userInsResult)) {
                        log.error("userInsResult:{}", userInsResult);
                        throw new ISQLException(ExceptionEnum.INSERT_RETURN_LINE_EXCEPTION.getErrorMsg());
                    }
                    if (!RESULT_RETURN_NUM.equals(userRoleInsResult)) {
                        log.error("userRoleInsResult:{}", userRoleInsResult);
                        throw new ISQLException(ExceptionEnum.INSERT_RETURN_LINE_EXCEPTION.getErrorMsg());
                    }
                } catch (ISQLException e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    log.error("e:{}", e.getMessage());
                    return false;
                }
                return true;
            }
        }));


    }


}